﻿
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;

namespace Anno.Repository
{
    /// <summary>
    /// 数据库配置
    /// </summary>
    public class ConnectionStringsOptions //: IConfigurableOptions
    {
        public ConnectionStringsOptions()
        {
          
        }
        public ConnectionStringsOptions Init()
        {
            try
            {
                var optionsConfiguration = Const.AppSettings.ConfigJson.GetSection("ConnectionStrings");
                var options = optionsConfiguration.Get<ConnectionStringsOptions>();
                // var options = Newtonsoft.Json.JsonConvert.DeserializeObject<ConnectionStringsOptions>( optionsConfiguration.Value);
                if (options != null)
                {
                    this.DbConfigs = options.DbConfigs;

                    this.DefaultDbNumber = options.DefaultDbNumber;
                    this.DefaultDbString = options.DefaultDbString;
                    this.DefaultDbType = options.DefaultDbType;
                }
            }
            catch { }
            return this;
        }
        /// <summary>
        /// 默认数据库编号
        /// </summary>
        public string DefaultDbNumber { get; set; }
        /// <summary>
        /// 默认数据库类型
        /// </summary>
        public string DefaultDbType { get; set; }
        /// <summary>
        /// 默认数据库连接字符串
        /// </summary>

        public string DefaultDbString { get; set; }
        /// <summary>
        /// 业务库集合
        /// </summary>
        public List<DbConfig> DbConfigs { get; set; }


        public bool Save()
        {
            try
            {
                var connectionStrings = this.SerializeObjectToJson();
                Anno.Const.AppSettings.SetAppSetting("ConnectionStrings", connectionStrings);
                return true;
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "Save ConnectionStrings");
                return false;
            }
        }
    }

    /// <summary>
    /// 数据库参数
    /// </summary>
    public class DbConfig
    {
        /// <summary>
        /// 数据库编号
        /// </summary>
        public string DbNumber { get; set; }
        /// <summary>
        /// 数据库类型
        /// </summary>
        public string DbType { get; set; }
        /// <summary>
        /// 数据库连接字符串
        /// </summary>

        public string DbString { get; set; }

        [Newtonsoft.Json.JsonIgnore]
        public bool IsDefault { get; set; }
    }
}
